<!--  -->
<template>
  <div>
    <el-card style="margin: 20px">
      <el-form :inline="true" :model="roleQuery" class="demo-form-inline">
        <el-form-item label="名称/角色名称">
          <el-input v-model="roleQuery.queryStr" placeholder="请输入查询关键字" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="getRoleListForm">查询</el-button>
          <el-button type="primary" icon="el-icon-check" @click="showAddRoleForm">新增角色</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card style="margin: 0px 20px">
      <div>
        <el-table :data="allRoleTree" style="width: 100%" :row-class-name="tableRowClassName" @sort-change="sortChange">
          <el-table-column type="expand">
            <template slot-scope="scope">
              <el-row
                v-for="(menu1,index1) in scope.row.children"
                :key="index1"
                style="height: auto"
                :class="['border-bottom',index1===0?'border-top':'','vcenterRole']"
              >
                <el-col :span="5">
                  <el-tag
                    effect="dark"
                    type="primary"
                    closable
                    @close="removeRoleThreeRight(scope.row, menu1,scope.row.children )"
                  >{{ menu1.name }}
                  </el-tag>
                  <i class="el-icon-caret-right" />
                </el-col>
                <el-col :span="15">
                  <el-row
                    v-for="(menu2,index2) in menu1.children"
                    :key="index2"
                    :span="6"
                    :class="['border-bottom',index2===0?'border-top':'']"
                  >
                    <el-col :span="8">
                      <el-tag
                        effect="dark"
                        type="warning"
                        closable
                        @close="removeRoleThreeRight(scope.row,menu2, menu1)"
                      >{{ menu2.name }}
                      </el-tag>
                      <i class="el-icon-caret-right" />
                    </el-col>
                    <el-col :span="10" style="margin: 2px">
                      <el-col v-for="(menu3,index3) in menu2.children" :key="index3" :span="7" style="margin: 2px">
                        <el-tag
                          effect="dark"
                          type="success"
                          closable
                          @close="removeRoleThreeRight(scope.row, menu3, menu2)"
                        >{{ menu3.name }}
                        </el-tag>
                      </el-col>
                    </el-col>
                  </el-row>
                </el-col>
              </el-row>
            </template>
          </el-table-column>
          <el-table-column
            prop="role.id"
            label="ID"
            width="260"
            align="center"
            sortable="custom"
            :class-name="sortRult('id')"
          />
          <el-table-column
            prop="role.name"
            label="名称"
            width="500"
            align="center"
            sortable="custom"
            :class-name="sortRult('name')"
          />
          <el-table-column
            prop="role.nameZh"
            label="角色名称"
            width="500"
            align="center"
            sortable="custom"
            :class-name="sortRult('nameZh')"
          />
          <el-table-column label="操作" width="270" align="center">
            <template slot-scope="scope">
              <el-button type="success" icon="el-icon-edit" circle @click="showEditRoleForm(scope.row.role)" />
              <el-button type="danger" icon="el-icon-delete" circle @click="delRoleById(scope.row.role.id)" />
              <el-button type="success" icon="el-icon-share" @click="getMenuByRoleId(scope.row.role.id)" />
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-dialog :title="opr+'角色'" :visible.sync="addRoleFormVisible">
        <el-form :model="addRoleForm">
          <el-form-item label="名称" :label-width="formLabelWidth">
            <el-input v-model="addRoleForm.name" autocomplete="off" />
          </el-form-item>
          <el-form-item label="角色名称" :label-width="formLabelWidth">
            <el-input v-model="addRoleForm.nameZh" autocomplete="off" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="closeAddRoleForm">取 消</el-button>
          <el-button type="primary" @click="commitAddRoleForm">确 定</el-button>
        </div>
      </el-dialog>
      <el-dialog v-if="addRoleMenuVisible" title="分配权限" :visible.sync="addRoleMenuVisible">
        <el-form :model="menuRoleParam" label="权限">
          <el-form-item>
            <el-tree
              ref="menuTree"
              :data="menuList"
              show-checkbox
              check-strictly
              node-key="id"
              :default-checked-keys="menuRoleParam.menuId"
              :props="props"
            />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="closeAddMenuRoleForm">取 消</el-button>
          <el-button type="primary" @click="commitAddMenuRoleForm">确 定</el-button>
        </div>
      </el-dialog>
      <div>
        <el-pagination
          ref="menuRoleTree"
          :current-page="roleQuery.pageIndex"
          :page-sizes="[ 5, 10]"
          :page-size="roleQuery.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script>
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
// 例如：import 《组件名称》 from '《组件路径》';
import { addMenuRoles, delMenuChildrenByRoleId, delRole, getListTree, getRoleMenu, saveRole, getRoleMenuById } from '@/api/role'

export default {
// import引入的组件需要注入到对象中才能使用
  components: {},
  data() {
    // 这里存放数据
    return {
      roleQuery: {
        queryStr: '',
        pageIndex: 1,
        pageSize: 5,
        sort: 'asckdsa_id'
      },
      allRoleTree: [],
      opr: '新增',
      total: 0,
      addRoleForm: { id: 0, name: '', nameZh: '' },
      addRoleFormVisible: false,
      formLabelWidth: '120px',
      menuList: {},
      menuRoleParam: { rid: 0, menuId: [] },
      addRoleMenuVisible: false,
      props: { label: 'name' }
    }
  },
  // 监听属性 类似于data概念
  computed: {},
  // 监控data中的数据变化
  watch: {},
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() {

  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    this.getRoleListForm()
    this.getMenuInit()
  },
  // 方法集合
  methods: {
    sortChange({ order, prop }) {
      console.log(prop, order)
      if (order === 'ascending') {
        this.roleQuery.sort = 'ascending_' + prop.substring(prop.indexOf('.') + 1)
      } else {
        this.roleQuery.sort = 'descending_' + prop.substring(prop.indexOf('.') + 1)
      }
      console.log(this.roleQuery)
      this.roleQuery.pageIndex = 1
      this.getRoleListForm()
    },
    sortRult(key) {
      let sort = ''
      if (this.roleQuery.sort) {
        sort = this.roleQuery.sort
      }
      return sort === `ascending_${key}` ? 'ascending' : 'descending'
    },
    closeAddMenuRoleForm() {
      this.menuRoleParam.rid = 0
      this.menuRoleParam.menuId = []
      this.addRoleMenuVisible = false
    },
    commitAddMenuRoleForm() {
      this.menuRoleParam.menuId = this.$refs.menuTree.getCheckedKeys()
      addMenuRoles(this.menuRoleParam).then((res) => {
        this.closeAddMenuRoleForm()
        this.$store.dispatch('menu/initRouters').then((data) => {
          // 将fmtRouters添加router路由中，即保存到router/index.js中
          this.$router.addRoutes(data) // 动态添加路由
        }).catch((err) => {
          console.log(err)
        })
        this.$store.dispatch('user/getInfo')
      })
      this.addRoleMenuVisible = false
    },
    getMenuInit() {
      getRoleMenu().then((res) => {
        this.menuList = res.data
      })
    },
    getMenuByRoleId(id) {
      this.menuRoleParam.rid = id
      getRoleMenuById(id).then((res) => {
        this.menuRoleParam.menuId = res.data
      })
      this.$nextTick(function() {
        this.addRoleMenuVisible = true
      })
    },
    handleSizeChange(val) {
      this.roleQuery.pageIndex = 1
      this.roleQuery.pageSize = val
      this.getRoleListForm()
    },
    handleCurrentChange(val) {
      this.roleQuery.pageIndex = val
      this.getRoleListForm()
    },
    getRoleListForm() {
      getListTree(this.roleQuery).then((res) => {
        this.allRoleTree = res.data.list
        this.total = res.data.total
      })
    },
    tableRowClassName({ row, rowIndex }) {
      if (rowIndex === 1) {
        return 'warning-row'
      } else if (rowIndex === 3) {
        return 'success-row'
      }
      return ''
    },
    delRoleById(id) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delRole(id).then((res) => {
          if (res.code === 200) {
            this.getRoleListForm()
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    showEditRoleForm(role) {
      this.addRoleFormVisible = true
      this.addRoleForm = role
    },
    showAddRoleForm() {
      this.addRoleFormVisible = true
      this.clearAddRoleForm()
    },
    closeAddRoleForm() {
      this.addRoleFormVisible = false
      this.clearAddRoleForm()
    },
    clearAddRoleForm() {
      this.opr = '新增'
      this.addRoleForm = { id: 0, name: '', nameZh: '' }
    },
    commitAddRoleForm() {
      saveRole(this.addRoleForm).then((res) => {
        if (res.code === 200) {
          this.addRoleFormVisible = false
          this.getRoleListForm()
        }
      })
    },
    removeRoleThreeRight(row, menu, partenMenu) {
      // eslint-disable-next-line no-unused-vars
      let delmenu = menu
      // eslint-disable-next-line no-unused-vars
      let delmenus = partenMenu.children
      if (partenMenu.children.length === 1) {
        row.children.forEach(item => {
          item.children.forEach(current => {
            if (current.id === partenMenu.children[0].parentId && current.children.length === 1) {
              delmenu = current
              delmenus = item.children
              if (item.id === current.parentId && item.children.length === 1) {
                delmenu = item
                delmenus = row.children
              }
            }
          })
        })
      }
      delMenuChildrenByRoleId(row.role.id, delmenu.id).then(res => {
        if (res.code === 200) {
          delmenus.splice(delmenus.indexOf(delmenu), 1)
        }
      })
    }
  }
}
</script>
<style scoped>
  .el-table .warning-row {
    background: oldlace;
  }

  .border-top {
    border-top: 1px solid #eee;
  }

  .border-bottom {
    border-bottom: 1px solid #eee;
    border-left: 1px solid #eee;
    border-right: 1px solid #eee;
  }

  .el-tag {
    margin: 7px;
  }

  .vcenterRole {
    display: flex;
    align-items: center;
  }
</style>
